<template>
  <div class="product-list-page">
    <div class="container">
      <h1>商品列表</h1>
      
      <!-- 搜索和筛选条件 -->
      <div class="search-box">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="searchKeyword" 
              placeholder="请输入商品名称" 
              clearable 
              @keyup.enter="handleSearch"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 商品列表 -->
      <div class="product-list" v-loading="loading">
        <el-row :gutter="20">
          <el-col 
            v-for="product in productList" 
            :key="product.id" 
            :span="6" 
            style="margin-bottom: 20px;"
          >
            <el-card :body-style="{ padding: '0px' }" class="product-card">
              <div class="product-image">
                <img 
                  :src="getProductImage(product)" 
                  :alt="product.name" 
                  class="image"
                  @error="handleImageError"
                />
              </div>
              <div style="padding: 14px;">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-price">￥{{ product.price }}</div>
                <div class="product-stock">库存：{{ product.stock }}</div>
                <div class="product-description">{{ product.description || '暂无描述' }}</div>
                <div class="product-actions">
                  <el-button type="primary" size="small" @click="viewProduct(product.id)">查看详情</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
      
      <div style="margin-top: 20px;">
        <router-link to="/" class="btn btn-primary">返回首页</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { queryProduct } from '@/api/productApi'

export default {
  name: 'ProductList',
  data() {
    return {
      searchKeyword: '',
      productList: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      loading: false
    }
  },
  mounted() {
    this.fetchProductList()
  },
  methods: {
    // 获取商品列表
    async fetchProductList() {
      this.loading = true
      try {
        const params = {
          keyword: this.searchKeyword,
          pageNum: this.pagination.current,
          pageSize: this.pagination.size
        }
        const res = await queryProduct(params)
        console.log('商品查询结果:', res)
        
        if (res.data) {
          // 根据后端返回的数据结构进行处理
          if (Array.isArray(res.data)) {
            // 如果直接返回数组
            this.productList = res.data
            this.pagination.total = res.data.length
          } else if (res.data.data) {
            // 如果返回分页结构 { data: [...], total: 100 }
            this.productList = res.data.data
            this.pagination.total = res.data.total || 0
          } else {
            // 其他情况
            this.productList = []
            this.pagination.total = 0
          }
        } else {
          this.productList = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败')
        this.productList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    
    // 搜索商品
    handleSearch() {
      this.pagination.current = 1
      this.fetchProductList()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = ''
      this.pagination.current = 1
      this.fetchProductList()
    },
    
    // 查看商品详情
    viewProduct(productId) {
      this.$router.push({ name: 'ProductDetail', params: { id: productId } })
    },
    
    // 处理分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchProductList()
    },
    
    // 处理当前页改变
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchProductList()
    },
    
    // 获取商品图片
    getProductImage(product) {
      if (product.fileName) {
        try {
          // 尝试返回实际图片路径
          return require(`@/assets/files/${product.fileName}`)
        } catch (error) {
          // 如果图片不存在，返回默认图片
          console.warn(`商品图片加载失败: ${product.fileName}`, error)
          return require('@/assets/images/default_product.jpg')
        }
      }
      // 如果没有fileName，返回默认图片
      return require('@/assets/images/default_product.jpg')
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = require('@/assets/images/default_product.jpg')
    }
  }
}
</script>

<style scoped>
.product-list-page {
  padding: 20px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.search-box {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.product-list {
  margin-bottom: 20px;
}

.product-card {
  height: 100%;
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.product-image {
  height: 200px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.product-image .image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  color: #ff4e00;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.product-stock {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-actions {
  text-align: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
</style>